package com.lagou.rpc.consumer.beanPostProcessor;

import com.lagou.rpc.consumer.anno.RpcDIService;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //获取这个类的所有属性
        Field[] fields = bean.getClass().getDeclaredFields();
        //循环遍历所有的fields
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            //获取单个指定注解
            RpcDIService annotation = field.getAnnotation(RpcDIService.class);
            if(annotation != null){
                Object ob = RpcClientProxy.createProxy(field.getType());
                field.setAccessible(true);
                try {
                    field.set(bean, ob);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }

}
